package com.shark.uh.exception;

import com.shark.uh.common.ApiResponse;
import com.shark.uh.enums.ResponseCode;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理
     *
     * @param ex BusinessException
     * @return ApiResponse
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResponse<Object> handleCustomException(BusinessException ex) {
        log.error(ex);
        return ApiResponse.error(ex.getResponseCode(), ex.getMessage());
    }

    /**
     * 请求参数缺失异常处理
     *
     * @param ex MissingServletRequestParameterException
     * @return ApiResponse
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ApiResponse<Object> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
        log.error(ex);
        return ApiResponse.error(ResponseCode.MISSING_REQUIRED_PARAMETER);
    }

    /**
     * 请求参数格式校验异常
     *
     * @param ex MethodArgumentNotValidException
     * @return ApiResponse
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error(ex);
        return ApiResponse.error(ResponseCode.PARAMETER_FORMAT_ERROR);
    }

    /**
     * 内部错误
     *
     * @param ex Exception
     * @return ApiResponse
     */
    @ExceptionHandler(Exception.class)
    public ApiResponse<Object> handleGeneralException(Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        return ApiResponse.error(ResponseCode.INTERNAL_SERVER_ERROR);
    }
}

